package com.cz.mydao.dao;

import com.cz.mydao.constant.Constant;
import com.cz.mydao.constant.SqlKey;
import com.cz.mydao.wrapper.SelectWrapper;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @descriptions: Mysql数据库dao层实现类
 * @author: Joker.
 * @date: 2024/12/27 14:45
 * @version: 1.0
 */
@Slf4j
public class MySQLBaseDao<T> extends AbstractBaseDao<T> {

    /**
     * 分页条件查询
     *
     * @param page     第几页
     * @param pageSize 每页多少条
     * @param wrapper  条件
     * @return 查询结果
     */
    @Override
    public List<T> pageQuery(Long page, Long pageSize, SelectWrapper wrapper) {
        // 拼接查询sql
        StringBuilder sql = new StringBuilder(wrapper.buildSql(tableName))
                // 拼接分页条件
                .append(SqlKey.LIMIT).append((page - 1) * pageSize).append(SqlKey.COMMA).append(pageSize);
        log.info(sql.toString());
        Connection connection = null;
        try {
            connection = connectionPool.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql.toString());

            // 为查询条件设置占位符
            List<Object> values = wrapper.getValues();
            for (int i = 0; i < values.size(); i++) {
                preparedStatement.setObject(i + 1, values.get(i));
            }
            // 执行查询并返回结果
            return executeQuerySql(preparedStatement);
        } catch (SQLException | InterruptedException e) {
            throw new RuntimeException(Constant.QUERY_FAIL, e);
        }
    }
}
